package com.hundsun.yr.universal.p2p.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.SpannableStringBuilder;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.hundsun.mobile.zwgt.R;
import com.hundsun.yr.universal.library.adapter.HolderAdapter;
import com.hundsun.yr.universal.library.adapter.ViewCreatorHelper;
import com.hundsun.yr.universal.library.adapter.ViewCreatorHelper.UpdateItem;
import com.hundsun.yr.universal.library.eventbus.EventCenter;
import com.hundsun.yr.universal.library.utils.SpannableStringBuilderUtils;
import com.hundsun.yr.universal.library.view.hsdialog.HSDialog;
import com.hundsun.yr.universal.library.view.hsdialog.HSDialog.HSDialogOnItemClickListener;
import com.hundsun.yr.universal.library.widget.HSButton;
import com.hundsun.yr.universal.library.widget.HSLoadMoreListView;
import com.hundsun.yr.universal.library.widget.HSLoadMoreListView.OnLoadMoreListener;
import com.hundsun.yr.universal.library.widget.HSSwipeRefreshLayout;
import com.hundsun.yr.universal.p2p.bean.MineTransfer;
import com.hundsun.yr.universal.p2p.bean.MyInvestBeen;
import com.hundsun.yr.universal.p2p.bean.UserInfo;
import com.hundsun.yr.universal.p2p.config.Constants;
import com.hundsun.yr.universal.p2p.config.Extras;
import com.hundsun.yr.universal.p2p.config.TaskConstants;
import com.hundsun.yr.universal.p2p.presenter.base.RequestPresenter;
import com.hundsun.yr.universal.p2p.presenter.impl.BaseListPresenterImpl;
import com.hundsun.yr.universal.p2p.ui.activity.MineInvestDetailActivity;
import com.hundsun.yr.universal.p2p.ui.activity.base.BaseFragment;
import com.hundsun.yr.universal.p2p.utils.BaseRequestTool2;
import com.hundsun.yr.universal.p2p.utils.CommTool;
import com.hundsun.yr.universal.p2p.view.base.BaseListView;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


/**
 * @version V1.0
 * @Title: TransferInFragment.java
 * @Description: 我的投资-待支付
 * @date 2016-1-5 下午2:51:14
 * @author:hejun.shen
 * @email:shenhj15971@hundsun.com
 * @replace author:
 * @replace date:
 */
public class TransferInFragment extends BaseFragment implements BaseListView, UpdateItem<MyInvestBeen>
        , OnRefreshListener, OnLoadMoreListener, HSDialogOnItemClickListener, OnItemClickListener {

    private RequestPresenter mPresenter = null;
    /**
     * 当前请求索引
     **/
    private int start = 0;
    /**
     * 下拉容器
     **/
    private HSSwipeRefreshLayout hsSwipeRefreshLayout = null;
    /**
     * listview 适配器
     **/
    private HolderAdapter<MyInvestBeen> mAdapter = null;
    /**
     * 可以加载更多的listview
     **/
    private HSLoadMoreListView lv_transferin = null;
    /**
     * 列表数据
     **/
    private List<MyInvestBeen> data = new ArrayList<MyInvestBeen>();
    /**
     * 撤销弹窗
     **/
    private HSDialog dialog_revoke = null;
    /**
     * 转让单据号
     **/
    private String transferVchrNo = null;
    /**
     * 撤销份额
     **/
    private String cancelNum = null;
    /**
     * 撤销索引
     **/
    private int mPosition = 0;
    /**
     * 获取zwgt格式请求时间
     **/
    private String zwgt_data;
    /**
     * 最下面一条的position
     */
    private int lastVisiblePosition;
    /**
     * 最下面那条的time
     */
    private Long time;
    private LayoutInflater mInflater;
    private RelativeLayout headerView;

    @Override
    protected void onFirstUserVisible() {
        // TODO Auto-generated method stub
        hsSwipeRefreshLayout.setRefreshing(true);
        mPresenter = new BaseListPresenterImpl(mContext, this, MineTransfer.BASEKEY);
        zwgt_data = BaseRequestTool2.getFormatedDateString();
        mPresenter.loadingData(TaskConstants.INVERST_LIST, getString(R.string.root_url_test) + getString(R.string.api_user_test) + TaskConstants.INVERST_LIST + "?type=" + 3,
                Constants.EVENT_REFRESH_DATA, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, getString(R.string.api_user_test) + TaskConstants.INVERST_LIST + "?type=" + 3,
                        sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), true);
    }

    @Override
    protected void onUserVisible() {
        // TODO Auto-generated method stub

    }

    @Override
    protected void onUserInvisible() {
        // TODO Auto-generated method stub

    }

    @Override
    protected View getLoadingTargetView() {
        // TODO Auto-generated method stub
        if (hsSwipeRefreshLayout == null) {
        }
        hsSwipeRefreshLayout = (HSSwipeRefreshLayout) findView(R.id.transferinRefreshLayout);
        return hsSwipeRefreshLayout;
    }

    @Override
    protected void initViewsAndEvents() {
        // TODO Auto-generated method stub
        if (mPresenter == null) {
            mPresenter = new BaseListPresenterImpl(mContext, this, "");
        }
        mPresenter.initialized();

        if (hsSwipeRefreshLayout == null) {
            hsSwipeRefreshLayout = (HSSwipeRefreshLayout) findView(R.id.transferinRefreshLayout);
        }

        lv_transferin = findView(R.id.lv_transferin);

        ViewCreatorHelper<MyInvestBeen> creatorHelper = new ViewCreatorHelper<MyInvestBeen>(R.layout.item_mine_invest_already, this);
        mAdapter = new HolderAdapter<MyInvestBeen>(mContext, creatorHelper.viewCreator());

        mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        headerView = (RelativeLayout) mInflater.inflate(R.layout.item_header_10dp, lv_transferin, false);
        lv_transferin.addHeaderView(headerView);

        lv_transferin.setAdapter(mAdapter);
        lv_transferin.setOnItemClickListener(this);
        hsSwipeRefreshLayout.setOnRefreshListener(this);
        lv_transferin.setOnLoadMoreListener(this);
    }


    @Override
    protected int getContentViewLayoutID() {
        // TODO Auto-generated method stub
        return R.layout.frag_mine_invest_transferin;
    }

    @Override
    protected void onEveComming(@SuppressWarnings("rawtypes") EventCenter eventCenter) {
        // TODO Auto-generated method stub
    }

    @Override
    protected boolean isBindEventBusHere() {
        // TODO Auto-generated method stub
        return false;
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> void refreshListData(List<T> result) {
        hsSwipeRefreshLayout.setRefreshing(false);
        lv_transferin.setLoadMoreEnabled(true);
        if (data.size() > 0) data.clear();
        if (result != null) {
            data.addAll((Collection<? extends MyInvestBeen>) result);
        }
        mAdapter.update(data);
    }

    @SuppressWarnings("unchecked")
    @Override
    public <T> void addMoreListData(List<T> result) {
        // TODO Auto-generated method stub
        lv_transferin.onLoadMoreComplete();

        if (result != null && result.size() > 0) {
            data.addAll((Collection<? extends MyInvestBeen>) result);
            lv_transferin.setLoadMoreEnabled(true);
        } else {
            lv_transferin.setLoadMoreEnabled(false);
        }
        mAdapter.update(data);
    }

    @Override
    public <T> void onFailure(String task_name) {
        // TODO Auto-generated method stub
        hsSwipeRefreshLayout.setRefreshing(false);
        lv_transferin.onLoadMoreComplete();
        if (data.size() > 0) data.clear();
        lv_transferin.setAdapter(mAdapter);
        mAdapter.update(data);
    }

    @Override
    public void refreshItem(View view, final int position, final MyInvestBeen invest) {
        /**年化收益**/
        TextView tv_annualincome = findView(view, R.id.tv_annualincome);
        SpannableStringBuilder spaBuilder = new SpannableStringBuilder();
        if (invest.rate != null && !invest.rate.isEmpty()) {
            spaBuilder = (SpannableStringBuilderUtils.sizeAndColorSpan
                    (CommTool.keep1Digits(invest.rate) + "%", "%", 14, mContext.getResources().getColor(R.color.cl_redformula_text_3837), true));
        } else {
            spaBuilder = (SpannableStringBuilderUtils.sizeAndColorSpan
                    ("0" + "%", "%", 14, mContext.getResources().getColor(R.color.cl_redformula_text_3837), true));
        }

        tv_annualincome.setText(spaBuilder);

        /**营销商品名称**/
        TextView tv_title = findView(view, R.id.tv_title);
        tv_title.setText(invest.name);

        /**累计收益**/
        TextView tv_income = findView(view, R.id.tv_income);

        try {
            BigDecimal touZi = new BigDecimal(invest.amount);
            BigDecimal rate = new BigDecimal(invest.rate).divide(new BigDecimal(100), 10, BigDecimal.ROUND_HALF_UP);
            BigDecimal term = new BigDecimal(invest.total_term);
            BigDecimal monthRate = rate.divide(new BigDecimal(12), 10, BigDecimal.ROUND_HALF_UP);

            BigDecimal expected_revenue = null;
            switch (invest.pay_method) {
                case "1":
                    //到期还本息付
                    expected_revenue = touZi.multiply(rate).multiply(term).divide(new BigDecimal(360), 5, BigDecimal.ROUND_HALF_UP);
                    break;
                case "2":
                    //按月还息到期还本
                    expected_revenue = touZi.multiply(monthRate).multiply(term);
                    break;
                case "3":
                    //等额本息
                    BigDecimal pow = (monthRate.add(new BigDecimal(1))).pow(term.intValue());
                    expected_revenue = (touZi.multiply(monthRate).multiply(pow).divide(pow.subtract(new BigDecimal(1)), 10, BigDecimal.ROUND_HALF_UP)).multiply(term).subtract(touZi);
                    break;
                case "4":
                    //等额本金
                    expected_revenue = touZi.multiply(monthRate).multiply((term.add(new BigDecimal(1)))).divide(new BigDecimal(2), 10, BigDecimal.ROUND_HALF_UP);
                    break;
            }
            tv_income.setText(SpannableStringBuilderUtils.sizeSpan(CommTool.moneyOneThousandsFormat(expected_revenue + ""), CommTool.moneyOneThousandsUnit(expected_revenue + ""), 14));
        } catch (Exception e) {
            e.printStackTrace();
            tv_income.setText("");
        }

        /**到期时间**/
        TextView tv_prd_progress = findView(view, R.id.tv_prd_progress);
        tv_prd_progress.setText(invest.getProgress(mContext));

        /**投资金额**/
        TextView tv_invsetmoney = findView(view, R.id.tv_invsetmoney);
        SpannableStringBuilder spaBuilder_investmoney = (SpannableStringBuilderUtils.colorSpan
                (getString(R.string._mineinvest_money, getString(R.string._yuan,CommTool.keep2Digits(invest.amount))), getString(R.string._yuan,CommTool.keep2Digits(invest.amount)), mContext.getResources().getColor(R.color.cl_redformula_text_3837)));
        tv_invsetmoney.setText(spaBuilder_investmoney);

        /**去支付**/
        HSButton btn_to_payment = findView(view, R.id.btn_to_payment);
        btn_to_payment.setVisibility(View.GONE);

        /**累计收益|预期收益**/
        TextView ev_accumulate_income = findView(view, R.id.ev_accumulate_income);
        ev_accumulate_income.setText(getString(R.string.expected_income));
        // TODO: 2017/5/24 还没有给出一个靠谱的标准，之后再改
        /**
         0	草稿
         10	已申请待付款
         15	银行处理中
         20	已付款
         30	计息中（暂时不用，同产品）
         50	已兑付（暂时不用，同产品）
         100	用户撤销
         110	超时关闭
         */

        // TODO: 2017/9/4 我不知道到期时间是哪一个字段
        /**投资期限**/
        TextView tv_incomemonet = findView(view, R.id.tv_incomemonet);
        if (invest.end_time == null){
            tv_incomemonet.setText(getString(R.string.expire_time_,""));
        } else {
            SpannableStringBuilder spaBuilder_incomemonet = (SpannableStringBuilderUtils.colorSpan
                    (getString(R.string.expire_time_,invest.end_time), invest.end_time, mContext.getResources().getColor(R.color.cl_redformula_text_3837)));
            tv_incomemonet.setText(spaBuilder_incomemonet);
        }

    }

    @Override
    public void onLoadMore() {
        // TODO Auto-generated method stub
        lastVisiblePosition = lv_transferin.getLastVisiblePosition();
        time = Long.valueOf(data.get(lastVisiblePosition - 2).ctime);
        zwgt_data = BaseRequestTool2.getFormatedDateString();
        mPresenter.loadingData(TaskConstants.INVERST_LIST, getString(R.string.root_url_test) + getString(R.string.api_user_test) + TaskConstants.INVERST_LIST + "?type=" + 3 + "&ctime=" + time,
                Constants.EVENT_LOAD_MORE_DATA, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, getString(R.string.api_user_test) + TaskConstants.INVERST_LIST + "?type=" + 3 + "&ctime=" + time,
                        sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), false);
    }

    @Override
    public void onRefresh() {
        // TODO Auto-generated method stub
        zwgt_data = BaseRequestTool2.getFormatedDateString();
        mPresenter.loadingData(TaskConstants.INVERST_LIST, getString(R.string.root_url_test) + getString(R.string.api_user_test) + TaskConstants.INVERST_LIST + "?type=" + 3,
                Constants.EVENT_REFRESH_DATA, BaseRequestTool2.getHearder(mContext, TaskConstants.TASK_GET, getString(R.string.api_user_test) + TaskConstants.INVERST_LIST + "?type=" + 3,
                        sharedPreferences.getShareProf(UserInfo.USER_NO), sharedPreferences.getShareProf(UserInfo.TOKENID), zwgt_data), false);
    }

    @Override
    public void onItemClick(Object o, int position) {
    }

    @Override
    public <T> void initializeViews(String task_name, T result) {
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (isFastDoubleClick()) {
            return;
        }
        if (position == 0 || position > data.size()) return;
        Bundle bundle = new Bundle();
        bundle.putSerializable(Extras.DATA, data.get(position - 1));
        readyGo(MineInvestDetailActivity.class, bundle);
    }

    /**
     * 防止按钮连续点击
     */
    private static long lastClickTime;

    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        if (time - lastClickTime < 500) {
            return true;
        }
        lastClickTime = time;
        return false;
    }
}
